//
//  RegisterConfirmViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/2/27.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "RegisterConfirmViewController.h"
#import "RegisterConfirmView.h"
#import "RegisterModelPack.h"
#import "UILabel+YBAttributeTextTapAction.h"
#import <Masonry.h>
#import "OpenDoc.h"
#import "ServeWebViewController.h"

@interface RegisterConfirmViewController ()<openDocDelegate>
@property(nonatomic,strong)RegisterConfirmView *rv;
@property(nonatomic,strong)OpenDoc *opendoc;
@end

@implementation RegisterConfirmViewController

#pragma mark 初始化
-(void)loadView{
    [super loadView];
    self.rv = [[RegisterConfirmView alloc] initWithFrame:self.view.bounds];
    self.view = self.rv;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"请填写注册信息";
    self.view.backgroundColor = [UIColor whiteColor];
    //单选框
    [self.rv.radioBtn addTarget:self action:@selector(radioBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //注册信息确认
    [self.rv.nextStepBtn addTarget:self action:@selector(nextStepBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.rv.passwordNumTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    [self.rv.rePasswordNumTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
    NSAttributedString *showAttString = [self getAttributeWith:@[@"《服务协议》",@"《法律声明及隐私权政策》"] string:self.rv.protocolLab.text orginFont:12 orginColor:ETColorWithRGB(153, 153, 153) attributeFont:12 attributeColor:ETColorWithRGB(49, 138, 255)];
    self.rv.protocolLab.attributedText = showAttString;
    [self.rv.protocolLab yb_addAttributeTapActionWithStrings:@[@"《服务协议》",@"《法律声明及隐私权政策》"] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
        NSString *message = [NSString stringWithFormat:@"点击了“%@”字符\nrange: %@\nindex: %ld",string,NSStringFromRange(range),(long)index];
        NSLog(@"%@",message);
        if(index ==0 ){
            NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"file/fuwu.pdf"];
            [self.opendoc downloadPDF:url];
        }else{
            NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"file/yingsi.pdf"];
            [self.opendoc downloadPDF:url];
        }
    }];
}
-(void)rebackDocPath:(NSString *)path{
    NSLog(@"路径:%@",path);
    ServeWebViewController *sev = [[ServeWebViewController alloc] init];
    sev.filePath = path;
    [self.navigationController pushViewController:sev animated:NO];
}
- (NSAttributedString *)getAttributeWith:(id)sender
                                  string:(NSString *)string
                               orginFont:(CGFloat)orginFont
                              orginColor:(UIColor *)orginColor
                           attributeFont:(CGFloat)attributeFont
                          attributeColor:(UIColor *)attributeColor
{
    __block  NSMutableAttributedString *totalStr = [[NSMutableAttributedString alloc] initWithString:string];
    [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:orginFont] range:NSMakeRange(0, string.length)];
    [totalStr addAttribute:NSForegroundColorAttributeName value:orginColor range:NSMakeRange(0, string.length)];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//    [paragraphStyle setLineSpacing:5.0f]; //设置行间距
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
    [paragraphStyle setAlignment:NSTextAlignmentLeft];
    [paragraphStyle setLineBreakMode:NSLineBreakByCharWrapping];
    [totalStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [totalStr length])];
    
    if ([sender isKindOfClass:[NSArray class]]) {
        
        __block NSString *oringinStr = string;
        __weak typeof(self) weakSelf = self;
        
        [sender enumerateObjectsUsingBlock:^(NSString *  _Nonnull str, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSRange range = [oringinStr rangeOfString:str];
            [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
            [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
            oringinStr = [oringinStr stringByReplacingCharactersInRange:range withString:[weakSelf getStringWithRange:range]];
        }];
        
    }else if ([sender isKindOfClass:[NSString class]]) {
        
        NSRange range = [string rangeOfString:sender];
        
        [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
        [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
    }
    return totalStr;
}

- (NSString *)getStringWithRange:(NSRange)range
{
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < range.length ; i++) {
        [string appendString:@" "];
    }
    return string;
}





-(void)radioBtnAction
{
    self.rv.radioBtn.selected = !self.rv.radioBtn.selected;
}

-(void)nextStepBtnAction
{
    NSString *pwdStr = self.rv.passwordNumTf.text;
    NSString *rePwdStr = self.rv.rePasswordNumTf.text;
    
    if (![AppTools checkPassword:pwdStr]) {
        [self showFailedResultTips:@"密码格式不一致" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    if (![AppTools checkPassword:rePwdStr]) {
        [self showFailedResultTips:@"密码格式错误" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    if (![pwdStr isEqualToString:rePwdStr]) {
        [self showFailedResultTips:@"两次密码不一致" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    if (!self.rv.radioBtn.selected) {
        [self showFailedResultTips:@"请点击同意服务协议" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    RegisterRequest *request = [[RegisterRequest alloc] init];
    request.recommendUserId = self.rv.inviteCodeNumTf.text;
    request.mobile = self.phoneNumStr;
    request.captcha = self.securityCodeNumStr;
    request.password = [self.rv.passwordNumTf.text md5];
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/regist/submitA0300"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [self RegisterSuccessWithResponse:responseObject];
        }
        
        
    } FailedHandler:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
-(void)RegisterSuccessWithResponse:(id )responseObject
{
    NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showSuccessResultTips:@"注册成功" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF completionBlock:^{
            NSInteger num = self.navigationController.viewControllers.count;
            if (num >= 3) {
                UIViewController *popVC =  self.navigationController.viewControllers[num - 3];
                [self.navigationController popToViewController:popVC animated:YES];
            }
        }];
    });
}

#pragma mark textField 监听
//输入框符合规则可以点击"下一步"
-(void)textFieldDidChange :(UITextField *)textField{
    
    NSString *pwdStr = self.rv.passwordNumTf.text;
    NSString *rePwdStr = self.rv.rePasswordNumTf.text;

    if (rePwdStr.length >= 6 && pwdStr.length >= 6) {
        //验证码输入的是6位  手机号输入框是手机号
        self.rv.nextStepBtn.userInteractionEnabled = YES;
        self.rv.nextStepBtn.backgroundColor = ETCONFIRMCOLOR;
    }else
    {
        self.rv.nextStepBtn.userInteractionEnabled = NO;
        self.rv.nextStepBtn.backgroundColor = ETCOMMONCOLOR;
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.rv.passwordNumTf resignFirstResponder];
    [self.rv.inviteCodeNumTf resignFirstResponder];
    [self.rv.rePasswordNumTf resignFirstResponder];
}
-(OpenDoc *)opendoc{
    if (!_opendoc) {
        _opendoc = [[OpenDoc alloc] init];
        _opendoc.delegate = self;
    }
    return _opendoc;
}


@end
